import { defineComponent, onMounted, ref, watch } from "vue";
import "./index.less";
import AMapView from "../AMap";
import { IAMapRef } from "../AMap/types";
import CardView from "../CardView";
import TextView from "../TextView";
import icon1 from "./asset/icon1.png";
import icon2 from "./asset/icon2.png";
import focus from "./asset/focusX1.png";
import normal from "./asset/normalX1.png";
import RowView from "../RowView";
import { getSize, getUserInfoUrl, phoneClick } from "@/command/apiTool";
import { DemonstrationSiteMapProps } from "./types";
import { useDetail } from "@/hooks";
import { useRouter } from "vue-router";
import { getAction } from "@/command/netTool";

export default defineComponent({
  name: "",
  props: DemonstrationSiteMapProps,
  setup(_, { expose }) {
    const router = useRouter();
    const amapRef = ref<IAMapRef>();
    const showModal = ref(false);
    let markers: any[] = [];
    let selectMarker: any = null;
    const position = localStorage.getItem("positionData") as string;
    const positionJSON = JSON.parse(position) as {
      latitude: string;
      longitude: string;
    };
    // 点位详情
    const pointInfo = ref({
      address: "",
      endTime: "",
      id: "",
      img: "",
      lat: "",
      lng: "",
      name: "",
      phone: "",
      startTime: "",
      distance: "",
      bx: "",
    });

    // 小户列表
    const [queryJdListByDh, detailConfig] = useDetail(
      getUserInfoUrl({
        dh: "/api/H5/farmerBase/listBase",
        xh: "/api/H5/farmerBase/listBase",
      }),
      []
    );
    // 监听参数变化
    watch(
      () => _.modelValue,
      (newValue) => {
        detailConfig.refresh(newValue);
      },
      {
        deep: true,
      }
    );
    const openPoint = (info: any) => {
      getAction("/api/H5/farmerBase/getMapDetail", {
        id: info.id,
        lat: positionJSON.latitude,
        lng: positionJSON.longitude,
      }).then((e) => {
        pointInfo.value = e;
      });
    };
    watch(
      () => queryJdListByDh.value,
      (newValue) => {
        markers.forEach((e) => amapRef.value?.map().remove(e));
        markers = [];
        newValue.forEach((e: any) => {
          var marker = new AMap.Marker({
            // size: new AMap.Size(25, 34),
            // 图标的取图地址
            // image: normal,
            // 图标所用图片大小
            // iconSize: [25, 34],
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(-9, -3),
            // icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            // icon: null,
            icon: normal,
            position: [e.lng, e.lat],
            anchor: "bottom-center",
            // imageSize: new AMap.Size(25, 34),
          });
          marker.on("click", () => {
            if (selectMarker == null) {
              selectMarker = marker;
            } else {
              selectMarker.setIcon(normal);
              selectMarker = marker;
            }
            marker.setIcon(focus);
            openPoint(e);
            showModal.value = true;
          });
          markers.push(marker);
          amapRef.value?.map().add(markers);
        });
        amapRef.value?.map().setFitView();
      }
    );
    const card1 = () => {
      const data = [
        {
          icon: icon1,
          onClick: () => {
            if (pointInfo.value.lat && pointInfo.value.lng) {
              location.href = `https://uri.amap.com/marker?position=${pointInfo.value.lng},${pointInfo.value.lat}`;
            }
          },
        },
        {
          icon: icon2,
          onClick: () => {
            phoneClick(pointInfo.value.phone);
          },
        },
      ];
      return (
        <div class="relative">
          <CardView title={pointInfo.value.name}>
            <div
              class="flex justify-between relative"
              onClick={() =>
                router.push(`/farmDetail?id=${pointInfo.value.id}`)
              }
            >
              <div class="flex flex-col mt-[10px]">
                <TextView class={"mb-[6px]"}>
                  联系方式：{pointInfo.value.phone}
                </TextView>
                <TextView class="!text-[#333333] font-bold mb-[6px]">
                  {pointInfo.value.address}
                </TextView>
                <TextView>
                  <span>距你{pointInfo.value.distance}</span>
                  <span class={"ml-4"}>步行{pointInfo.value.bx}</span>
                </TextView>
              </div>
              <RowView>
                {data.map((e) => {
                  return (
                    <img
                      src={e.icon}
                      class="w-[40px] h-[40px] first-of-type:mr-[10px]"
                      onClick={(ev) => {
                        ev.stopPropagation();
                        ev.preventDefault();
                        e.onClick && e.onClick();
                      }}
                    />
                  );
                })}
              </RowView>
            </div>
          </CardView>
          <div
            class={"openTime"}
            onClick={() => router.push(`/farmDetail?id=${pointInfo.value.id}`)}
          >
            <div>
              {pointInfo.value.startTime}-{pointInfo.value.endTime}
            </div>
            <div>开放时间</div>
          </div>
        </div>
      );
    };
    const card2 = () => {
      return (
        <CardView
          title="现场照片"
          right={() => (
            <span
              class={"text-[#666666] text-[14px]"}
              onClick={() =>
                router.push(`/farmDetail?id=${pointInfo.value.id}`)
              }
            >
              查看更多
            </span>
          )}
          class="mt-[12px]"
        >
          <div class="overflow-x-scroll flex ">
            {pointInfo.value.img &&
              pointInfo.value.img.split(",").map((e) => {
                return (
                  <img
                    class="w-[85px] h-[85px] mr-[10px]"
                    style={{ borderRadius: getSize(8) }}
                    src={e}
                  />
                );
              })}
          </div>
        </CardView>
      );
    };
    const renderModal = () => {
      if (!showModal.value) return null;
      return (
        <div
          class={[
            "absolute right-0 left-0 bottom-[20px] z-10 h-[280px]",
            "amap-animation",
          ]}
        >
          {card1()}
          {card2()}
        </div>
      );
    };
    return () => {
      return (
        <div class="relative flex flex-col flex-1">
          <AMapView ref={amapRef} class="flex-1 h-full" />
          {renderModal()}
        </div>
      );
    };
  },
});
